package com.xinyue.center.dao;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.common.utils.Md5Utils;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.dao.redis.EnumRedisKey;
import com.xinyue.dao.GameRepositoryCacheDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Repository
public class AccountDao {
    private static final String FACTOR = "DXjdsdfsdfsdfserwefsdfgfsdfdswe";
    private static final String MD5_ENCODE = "utf8";
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private NacosDiscoveryProperties properties;
    private GameRepositoryCacheDao<Account, String> gameRepositoryCacheDao;

    @PostConstruct
    public void init() {
        String namespace = properties.getNamespace();
        gameRepositoryCacheDao = new GameRepositoryCacheDao<>(namespace, redisTemplate, EnumRedisKey.Account, accountRepository);
    }

    public Optional<Account> getAccountById(String accountId) {
        return gameRepositoryCacheDao.findById(accountId, Account.class);
    }


    /**
     * <p>
     * Description:使用算法，根据用户名生成一个唯的ID
     * </p>
     *
     * @param username
     * @return
     * @author wang guang shuai
     * @date 2020年3月13日 下午3:39:24
     */
    public String useranmeGenerateAccountId(String username) {
        String value = username + username.toLowerCase() + "_" + username.toUpperCase();
        String newValue = Md5Utils.getMD5(value, MD5_ENCODE);
        String accountId = Md5Utils.getMD5((value + "_" + newValue), MD5_ENCODE);
        return accountId;
    }
}
